package com.ruoyi.web.controller.combat.apprisk;

import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.combat.domain.apprisk.AddApp;
import com.ruoyi.combat.domain.apprisk.CombatApplication;
import com.ruoyi.combat.service.apprisk.ICombatAppTaskService;
import com.ruoyi.combat.service.apprisk.ICombatApplicationService;
import com.ruoyi.combat.service.apprisk.YueQuanService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2024-07-30
 */
@RestController
@RequestMapping("/combat/application")
@Api(tags = "课题一：应用服务检测-APK管理接口")
@Slf4j
public class CombatApplicationController extends BaseController
{
    @Autowired
    private ICombatApplicationService combatApplicationService;

    @Autowired
    private YueQuanService yueQuanService;

    @Autowired
    private ICombatAppTaskService combatAppTaskService;

    @Value("${apk.uploadPath}")
    private String uploadPath;

    /**
     * 查询APK列表
     */
    @PreAuthorize("@ss.hasPermi('system:application:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询全部APK列表")
    public TableDataInfo list(CombatApplication combatApplication)
    {
        startPage();
        List<CombatApplication> list = combatApplicationService.selectCombatApplicationList(combatApplication);
        return getDataTable(list);
    }

    /**
     * 导出全部APK列表
     */
    @PreAuthorize("@ss.hasPermi('system:application:export')")
    @Log(title = "导出全部APK列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出全部APK列表")
    public void export(HttpServletResponse response, CombatApplication combatApplication)
    {
        List<CombatApplication> list = combatApplicationService.selectCombatApplicationList(combatApplication);
        ExcelUtil<CombatApplication> util = new ExcelUtil<CombatApplication>(CombatApplication.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取APK详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:application:query')")
    @GetMapping(value = "/{appid}")
    @ApiOperation(value = "获取APK详细信息")
    public AjaxResult getInfo(@PathVariable("appid") Long appid)
    {
        return success(combatApplicationService.selectCombatApplicationByAppid(appid));
    }

    /**
     * 新增APK
     */

    @PostMapping
    @ApiOperation(value = "新增APK")
    @Anonymous
    public AjaxResult add(@RequestBody CombatApplication combatApplication)
    {
        return toAjax(combatApplicationService.insertCombatApplication(combatApplication));
    }

    /**
     * 修改APK
     */
    @PreAuthorize("@ss.hasPermi('system:application:edit')")
    @Log(title = "修改APK", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改APK")
    public AjaxResult edit(@RequestBody CombatApplication combatApplication)
    {
        return toAjax(combatApplicationService.updateCombatApplication(combatApplication));
    }

    /**
     * 删除APK
     */
    @PreAuthorize("@ss.hasPermi('system:application:remove')")
    @Log(title = "删除APK", businessType = BusinessType.DELETE)
	@DeleteMapping("/{appids}")
    @ApiOperation(value = "删除APK")
    public AjaxResult remove(@PathVariable Long[] appids)
    {
        return toAjax(combatApplicationService.deleteCombatApplicationByAppids(appids));
    }

    /**
     * 获取APK的风险信息
     */
    @PreAuthorize("@ss.hasPermi('system:application:query')")
    @GetMapping(value = "/risk/{appid}")
    @ApiOperation(value = "获取APK详细信息")
    public TableDataInfo getRiskInfo(@PathVariable("appid") Long appid)
    {

        return getDataTable(null);
    }

    @ApiOperation(value = "文件上传请求")
    @PostMapping("upload")
    public AjaxResult uploadApp(MultipartFile file)
    {
        return AjaxResult.success(combatApplicationService.uploadApp(file));
    }

    /**
     * app上传apk
     * private String name;
     *     private String pkgname;
     *     private String verisonName;
     *     private String icon;
     *     private String path;
     */
//    @Anonymous
    @PostMapping("addApp")
    @ApiOperation(value = "app上传apk")
    public AjaxResult addApp(@RequestParam(value="file",required = false) MultipartFile file,
                             @RequestParam(value = "name",required = false)String name,
                             @RequestParam(value = "pkgname",required = false)String pkgname,
                             @RequestParam(value = "versionName",required = false)String versionName,
                             @RequestParam(value = "versionName",required = false)String recordno,
                             @RequestParam(value = "icon",required = false)String icon){

        combatApplicationService.addApp(file,name,pkgname,versionName,icon,recordno);
        return success();
    }


    @Anonymous
    @PostMapping("check")
    @ApiOperation(value = "检测应用")
    public AjaxResult check(@RequestParam(value = "name",required = false)String name,
                            @RequestParam(value = "pkgname",required = false)String pkgname,
                            @RequestParam(value = "versionName",required = false)String versionName){

        return success(yueQuanService.service(name, pkgname, versionName));
    }
    /**
     * 获取用户已经检测的app列表信息
     * @return
     */
    @GetMapping("getAppWarnList")
    @ApiOperation(value = "获取用户已经检测的app列表信息")
    public AjaxResult getAppWarnList(){
        return success(combatApplicationService.getAppWarnList());
    }
    /**
     * 获取用户已经检测的app分析信息
     * @return
     */
    @GetMapping("getAppAnalyseInfo")
    @ApiOperation(value = "获取用户已经检测的app分析信息")
    public AjaxResult getAppAnalyseInfo(){
        List<Map> appAnalyseInfo = combatApplicationService.getAppAnalyseInfo();
        return success(appAnalyseInfo);
    }
    @GetMapping("getAppAnalyseInfo1")
    @ApiOperation(value = "获取用户已经检测的app分析信息")
    public AjaxResult getAppAnalyseInfo1(){
        List<Map> appAnalyseInfo = combatApplicationService.getAppAnalyseInfo1();
        return success(appAnalyseInfo);
    }

    /**
     * 算法三
     * 回传apk检测结果
     * @param jsonData
     * @return
     */
    @Anonymous
    @PostMapping("sendCheckResult")
    public AjaxResult sendCheckResult(@RequestBody List<Map> jsonData)
    {
        combatAppTaskService.sendCheckResult(jsonData);
        return AjaxResult.success();
    }

    /**
     * 算法1回传apk检测结果
     * @param data
     * @return
     */
    @Anonymous
    @PostMapping("sendCheck1Result")
    public AjaxResult sendCheck1Result(@RequestBody Map data)
    {
        combatAppTaskService.sendCheck1Result(data);
        return AjaxResult.success();
    }

    @GetMapping("/appTypeCount")
    @ApiOperation(value = "应用类型统计")
    public AjaxResult appTypeCount() {
        return success(combatApplicationService.appTypeCount());
    }

    @GetMapping("/download")
    @Anonymous
    public void fileDownload(Long appid, HttpServletResponse response)
    {
        try
        {
            CombatApplication combatApplication = combatApplicationService.selectCombatApplicationByAppid(appid);
            if(combatApplication!=null) {
                String appPath = combatApplication.getAppPath();

                String realFileName = combatApplication.getAppName()+".apk";
                String filePath =uploadPath+File.separator+appPath;

                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                FileUtils.setAttachmentResponseHeader(response, realFileName);
                FileUtils.writeBytes(filePath, response.getOutputStream());

            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }



    @GetMapping("/delApp")
    public AjaxResult delApp(@RequestParam(value = "pkgname")String pkgname,
                             @RequestParam(value = "versionName")String versionName)
    {
        return success(combatApplicationService.delApp(pkgname,versionName));
    }

    /**
     * 采集应用宝数据
     * @return
     */
    @Anonymous
    @GetMapping("/collectApp")
    public AjaxResult collectApp()
    {
        combatApplicationService.collectApp();
        return success();
    }


}
